package com.iams.activiti8.config;

import com.iams.common.core.domain.entity.SysUser;
import com.iams.system.service.ISysUserService;
import org.activiti.api.runtime.shared.identity.UserGroupManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class SpringSecurityGroupManager implements UserGroupManager {
    
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public List<String> getUserGroups(String userId) {
        try {
            // 将ID转换为用户名
            Long userIdLong = Long.parseLong(userId);
            SysUser user = sysUserService.selectUserById(userIdLong);
            if (user != null) {
                // 使用用户名获取角色
                String roleGroup = sysUserService.selectUserRoleGroup(user.getUserName());
                return List.of(roleGroup.split(","));
            }
        } catch (Exception e) {
            // 异常情况返回空列表
        }
        return List.of();
    }

    @Override
    public List<String> getUserRoles(String userId) {
        return getUserGroups(userId);
    }

    @Override
    public List<String> getGroups() {
        return List.of();
    }

    @Override
    public List<String> getUsers() {
        try {
            SysUser user = new SysUser();
            List<SysUser> users = sysUserService.selectUserList(user);
            // 返回用户名列表
            return users.stream()
                    .map(SysUser::getUserName)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            return List.of();
        }
    }
}
